package com.ruoyi.manager.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.manager.domain.City;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.manager.domain.Rank;
import com.ruoyi.manager.mapper.RankMapper;
import com.ruoyi.manager.service.IRankService;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @program: ruoyi
 * @description: ${description}
 * @author: yuxiang
 * @create: 2021-09-03 16:59
 */
@Service
public class RankServiceImpl extends ServiceImpl<RankMapper, Rank> implements IRankService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public List<Rank> getRankTree() {
        BoundValueOperations<String, String> ops = redisTemplate.boundValueOps(Constants.RANK_TREE);
        String rankJson = ops.get();
        if (StringUtils.isNotEmpty(rankJson)) {
            List<Rank> rankList = (List<Rank>) JSON.parseObject(rankJson, new TypeReference<List<Rank>>() {
            });
            return rankList;
        }

        List<Rank> rankList = baseMapper.selectList(null);
        List<Rank> rankTree = rankList.stream()
                .filter(item -> Objects.equals(1, item.getType()))
                .map(item -> {
                    item.setChildrenList(getChildrenList(item, rankList));
                    return item;
                }).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(rankTree)){
            ops.set(JSON.toJSONString(rankTree), 30, TimeUnit.DAYS);
        }
        return rankTree;
    }

    private List<Rank> getChildrenList(Rank rank, List<Rank> rankList) {
        if (CollectionUtil.isEmpty(rankList)) {
            return null;
        }
        return rankList.stream()
                .filter(item -> Objects.equals(rank.getId(), item.getPid()))
                .map(item -> {
                    item.setChildrenList(getChildrenList(item, rankList));
                    return item;
                }).collect(Collectors.toList());
    }
}
